package client.global.commlib.network.converterfactory

import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonIOException
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonToken
import okhttp3.ResponseBody
import retrofit2.Converter

class CustomGsonResponseConverter : Converter<ResponseBody, Any> {

    val gson: Gson
    val adapter: TypeAdapter<Any>

    constructor(gson: Gson, adapter: TypeAdapter<Any>) {
        this.gson = gson
        this.adapter = adapter
    }

    override fun convert(value: ResponseBody): Any? {
        val jsonReader = gson.newJsonReader(value.charStream())
        return try {
            val result: Any = adapter.read(jsonReader)
            Log.d("CustomReader", result.toString())
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw JsonIOException("JSON document was not fully consumed.")
            }
            result
        } finally {
            value.close()
        }
    }
}